/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.ecommerce.sessionService;

import br.com.ecommerce.entity.impl.Endereco;
import br.com.ecommerce.entity.impl.Usuario;
import br.com.ecommerce.util.ejb.AbstractService;
import br.com.ecommerce.util.view.JsfUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

/**
 *
 * @author rpateixeira
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class UsuarioServiceSession extends AbstractService<Usuario>{
    
    public List<Usuario> findInOrderByName(String nomeUsuario){
        Map<String,Object> args = new HashMap<String, Object>();
        args.put("name", nomeUsuario);
        return persistence.findByNamed("Usuario.findInOrderByName", args);
    }

    public boolean isUsuarioLogado(Usuario usuario){
        Map<String,Object> args = new HashMap<String, Object>();
        args.put("username", usuario.getUsername());
        args.put("password", usuario.getPassword());
        List<Usuario>result=persistence.find("select us from "+getEntityType().getSimpleName()+" us where us.username=:username and us.password=:password", args);
        if(!result.isEmpty()){
            //TODO Descomentar a linha abaixo somente quando for usar a aplicação
            //em execução de teste não é possivel usar o HttpSession
            JsfUtil.setAtributeInSession("USUARIO_LOGADO",result.get(0));
            return true;
        }
        return false;
    }

    public List<Endereco>findEnderecoByUsuario(Usuario usuario){
        Map<String,Object> args = new HashMap<String, Object>();
        args.put("usuario", usuario);
        return persistence.find("SELECT oEntidade FROM "+Endereco.class.getSimpleName()+" oEntidade where oEntidade.usuario=:usuario", args);
    }

    public Endereco findEnderecoById(Long idEndereco){
        return persistence.getPojo(Endereco.class, idEndereco);
    }
}
